﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using log4net;
using System.Reflection;

namespace Cn.Edwon.Data {
    public class ADO4Sqlite3 : AccessSupport, ICommonProcess {
        public static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        public ADO4Sqlite3(String connString) {
            base.ConnectString = connString;
        }
        public ADO4Sqlite3(String dataSource, Boolean pooling, Boolean failIfMissing) {
            base.ConnectString = "Data Source=" + dataSource + ";Pooling=" + pooling.ToString() + ";FailIfMissing=" + failIfMissing.ToString();
        }
        public ADO4Sqlite3(String dataSource, Boolean pooling, Boolean failIfMissing, String password) {
            base.ConnectString = "Data Source=" + dataSource + ";Pooling=" + pooling.ToString() + ";FailIfMissing=" + failIfMissing.ToString();
            if (String.IsNullOrEmpty(password)) {
                base.ConnectString += ";Password=" + password;
            }
        }
        
        #region ICommonProcess 成员

        public int CommonUpdateAction(string tsql) {
            this.Sql = tsql;
            log.Debug("tsql:[" + tsql + "]");
            using (SQLiteConnection conn = new SQLiteConnection(ConnectString)) {
                log.Debug("Database connect succeed");
                SQLiteCommand odc = new SQLiteCommand(tsql, conn);
                conn.Open();
                log.Debug("Connection opened");
                return odc.ExecuteNonQuery();
            }
        }

        public DataSet CommonSelectAction(string tsql, string tableName) {
            this.Sql = tsql;
            log.Debug("tsql:[" + tsql + "]");
            using (SQLiteConnection conn = new SQLiteConnection(ConnectString)) {
                log.Debug("Database connect succeed");
                using (SQLiteDataAdapter da = new SQLiteDataAdapter(tsql, conn)) {
                    if (da != null) {
                        log.Debug("DataAdapter allready");
                    } else {
                        log.Error("DataAdapter error");
                        return null;
                    }
                    DataSet ds = new DataSet();
                    da.Fill(ds, tableName);
                    log.Debug("Fill data to dataset succeed");
                    return ds;
                }
            }
        }

        #endregion
    }
}
